# -*- coding: utf-8 _*_
# @Software : PyCharm
# @File : app.py
# @TIME : 2024/10/20 12:10

from flask import Flask, request, jsonify, render_template
from config import Config
from models import db, WarnRule
import redis

app = Flask(__name__)
app.config.from_object(Config)
db.init_app(app)

r = redis.StrictRedis(
    host=app.config['REDIS_HOST'],
    port=app.config['REDIS_PORT'],
    password=app.config['REDIS_PASSWORD'],
    db=app.config['REDIS_DB'],
    decode_responses=True
)


@app.route('/')
def index():
    return render_template('index.html')

@app.route('/search_mac_prefix.html')
def search_mac_prefix():
    return render_template('search_mac_prefix.html')

@app.route('/search_global_mac.html')
def search_global_mac():
    return render_template('search_global_mac.html')

@app.route('/add_mac_prefix.html')
def add_mac_prefix():
    return render_template('add_mac_prefix.html')


#查询MAC前缀是否在告警库中
@app.route('/search', methods=['GET'])
def search_by_mac_prefix():
    mac_prefix = request.args.get('mac_prefix')

    if not mac_prefix:
        return jsonify({"error": "mac_prefix is required"}), 400

    # 在 Redis 中查找 MAC 前缀
    result = r.hget('warn_rule_info', mac_prefix)

    if result:
        return jsonify({
            "mac_prefix": mac_prefix,
            "type": result
        })
    else:
        return jsonify({"message": f"{mac_prefix} 不在告警库中！"}), 404



# 查询 Redis 中的 MAC 前缀信息(全球)
@app.route('/search_redis', methods=['GET'])
def search_redis_by_mac_prefix():
    mac_prefix = request.args.get('mac_prefix')

    if not mac_prefix:
        return jsonify({"error": "mac_prefix is required"}), 400

    # 在 Redis 中查找 MAC 前缀
    result = r.hget('dict_mac_org', mac_prefix)

    if result:
        return jsonify({
            "mac_prefix": mac_prefix,
            "info": result
        })
    else:
        return jsonify({"message": f"{mac_prefix} 不在全球MAC库中！"}), 404


#录入MAC告警库
@app.route('/insert', methods=['POST'])
def insert_mac_prefix():
    data = request.get_json()
    mac_prefix = data.get('mac_prefix')
    vendor = data.get('vendor')
    type = data.get('type')

    if not mac_prefix or not vendor or not type:
        return jsonify({"success": False, "message": "缺少参数"}), 400

    # 在数据库中插入新记录
    try:
        new_warn_rule = WarnRule(
            mac_prefix=mac_prefix,
            remark=vendor,
            type=type
        )
        db.session.add(new_warn_rule)
        db.session.commit()

        # 将数据插入 Redis
        r.hset('warn_rule_info', mac_prefix, type)

        return jsonify({"success": True, "message": "录入成功"})
    except Exception as e:
        db.session.rollback()
        return jsonify({"success": False, "message": str(e)})




if __name__ == '__main__':
    app.run(debug=True,port=8080)

